package com.luoran.bartalks.api;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.annotation.OperationLog;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.BtContainer;
import com.luoran.bartalks.entity.biz.BtMateriel;
import com.luoran.bartalks.entity.biz.BtPackingListMateriel;
import com.luoran.bartalks.entity.biz.BtPlanBiz;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtProject;
import com.luoran.bartalks.service.IBtContainerService;
import com.luoran.bartalks.service.IBtMaterielService;
import com.luoran.bartalks.service.IBtPackingListMaterielService;
import com.luoran.bartalks.service.IBtPackingListService;
import com.luoran.bartalks.service.IBtPlanBizService;
import com.luoran.bartalks.service.IBtPlanDetailsService;
import com.luoran.bartalks.service.IBtPlanEntryService;
import com.luoran.bartalks.service.IBtProjectService;
import com.luoran.bartalks.utils.EnumOperationType;

/**
 * 货物装载的Controller
 * 
 * @author 11057
 *
 */
@RestController
@RequestMapping("/api/loading")
public class LoadingApi {

	@Autowired
	private IBtPlanBizService planBizService;

	@Autowired
	private IBtPlanEntryService planEntryService;

	@Autowired
	private IBtProjectService projectService;

	@Autowired
	private IBtContainerService containerService;

	@Autowired
	private IBtMaterielService materielService;

	@Autowired
	private IBtPackingListService packingListService;

	@Autowired
	private IBtPackingListMaterielService packingListMaterielService;

	@Autowired
	private IBtPlanDetailsService planDetailsService;

	private static final Logger log = LoggerFactory.getLogger(LoadingApi.class);

	// 扫描容器
	@RequestMapping("/scanContainer")
	public String scanContainer(String qrcodeStr) {
		log.info("识别到的二维码信息[{}]", qrcodeStr);
		JSONObject res = new JSONObject();
		// qrcode校验
		if (StringUtils.isEmpty(qrcodeStr)) {
			res.put("state", false);
			res.put("msg", "无效二维码,请重新扫描!");
			return res.toJSONString();
		}
		// 需要根据容器二维码和公司ID 校验容器
		BtContainer persistentContainer = containerService.getContainerByQrcodeAndCompanyId(qrcodeStr,
				AppUser.get().getCompanyId());
		if (persistentContainer != null) {
			log.info("获取容器信息成功");
			JSONObject containerObj = new JSONObject();
			containerObj.put("containerId", persistentContainer.getId());// 容器ID
			containerObj.put("containerCode", persistentContainer.getContainerCode());// 容器编码
			containerObj.put("containerName", persistentContainer.getContainerName());// 容器名称
			if (persistentContainer.getContainerType() == 0) {
				containerObj.put("containerType", "仓储容器");// 容器类型
			} else if (persistentContainer.getContainerType() == 1) {
				containerObj.put("containerType", "运输容器");// 容器类型
			} else {
				containerObj.put("containerType", "未定义容器");// 容器类型
			}
			containerObj.put("containerLength", persistentContainer.getLongs());// 长
			containerObj.put("containerWidth", persistentContainer.getWide());// 宽
			containerObj.put("containerHeight", persistentContainer.getHigh());// 高
			containerObj.put("containerDeadWeight", persistentContainer.getDeadWeight());// 自重
			containerObj.put("containerBearWeight", persistentContainer.getBearWeight());// 承重
			containerObj.put("containerPermission", persistentContainer.getPermission());// 许可,牌照
			res.put("state", true);
			res.put("data", containerObj);
			return res.toJSONString();
		} else {
			res.put("state", false);
			res.put("msg", "请重新扫描二维码");
			return res.toJSONString();
		}
	}

	/*
	 * // 选择容器
	 * 
	 * @RequestMapping("ChoseContainers") public JSONObject ChoseContainers() {
	 * JSONObject res = new JSONObject(); List<BtContainer> containers =
	 * containerService.getContainerBycompanyId(AppUser.get().getCompanyId());
	 * res.put("data", containers); return res; }
	 */

	// 扫描货物
	@RequestMapping("/scanMateriel")
	@OperationLog(EnumOperationType.LOADING)
	public String scanMateriel(String qrcodeStr, String projectId, String planId, String planPositionId,
			String containerId) {
		log.info("识别到的二维码信息[{}],项目id[{}],计划id[{}],计划途径点关系id[{}],容器id[{}]", qrcodeStr, projectId, planId, planPositionId,
				containerId);
		JSONObject res = new JSONObject();
		// qrcode校验
		if (StringUtils.isEmpty(qrcodeStr)) {
			res.put("state", false);
			res.put("msg", "无效二维码,请重新扫描!");
			return res.toJSONString();
		}
		// 获取当前容器信息.
		BtContainer persistentContainer = containerService.getContainerById(containerId);
		// 根据箱单物料二维码和公司id查询
		BtPackingListMateriel packingListMateriel = packingListMaterielService
				.getItemByMaterielQrcodeAndCompanyId(qrcodeStr, AppUser.get().getCompanyId());
		if (packingListMateriel != null) {
			log.info("获取物料箱单记录成功");
			String materielId = packingListMateriel.getMaterielId();
			// 根据物料id,查询物料
			BtMateriel persistentMateriel = materielService.getBtMaterielByIdAndCompanyId(materielId,
					AppUser.get().getCompanyId());
			// 根据箱单物料id,查询当前点该物料是否存在装货记录,
			BtPlanBiz persistentPlanBiz = planBizService
					.getItemByPackingListMaterielIdAndPlanPositionId(packingListMateriel.getId(), planPositionId, 10);
			// 如果不存在,添加记录, 如果存在 跳过.避免重复扫描重复添加
			if (persistentPlanBiz == null) {
				// 装卸货记录对象
				BtPlanBiz planBiz = new BtPlanBiz();
				planBiz.setProjectId(projectId);// 项目id
				planBiz.setPlanId(planId);// 计划id
				planBiz.setPlanPositionId(planPositionId);// 计划位置关系表id.(计划途径点记录表id)
				planBiz.setMaterielId(materielId);
				planBiz.setMaterielName(persistentMateriel.getMaterielName());
				planBiz.setBizType(10);// 装货
				planBiz.setBizDate(new Date());// 时间
				planBiz.setBizUser(AppUser.get().getId());// 操作人
				planBiz.setContainerId(containerId);
				planBiz.setPlanPkgMaterielId(packingListMateriel.getId());// 箱单物料记录表id
				planBizService.addPlanBiz(planBiz);
				// 计划自动启动
				int started = planDetailsService.getStartedById(planId);
				if (started == 1) {
					BtPlanDetails plan = new BtPlanDetails();
					plan.setId(planId);
					plan.setStarted(0);
					planDetailsService.updatePlan(plan);
					BtProject project = new BtProject();
					project.setId(planDetailsService.getItemById(plan.getId()).getProjectId());
					project.setStarted(0);
					projectService.updateTemplateById(project);
				}
				// 判断是否是计划中的货物
				int check = packingListService.checkByPackingListIdAndPlanId(packingListMateriel.getPackingListId(),
						planId, AppUser.get().getCompanyId());
				// 非该计划货物但是同公司下的可以捎带,自动上报异常,
				if (check == 0) {
					// 自动异常上报
					String exception = planEntryService.getPlanEntryById(planPositionId).getException();
					if (exception == null) {
						exception = "";
					}
					planEntryService.updateExceptionInfo(planPositionId, planId,
							exception + "\n编码为:" + packingListMateriel.getMaterielCode() + " 的"
									+ packingListMateriel.getMaterielName() + "不是计划中的货物,但是在"
									+ planEntryService.getPlanEntryById(planPositionId).getAddressName() + "装载至编码为:"
									+ persistentContainer.getContainerCode() + "的"
									+ persistentContainer.getContainerName() + "中");
				}
			}
			JSONObject obj = new JSONObject();
			obj.put("containerId", persistentContainer.getId());// 容器ID
			obj.put("containerCode", persistentContainer.getContainerCode());// 容器编码
			obj.put("containerName", persistentContainer.getContainerName());// 容器名称
			if (persistentContainer.getContainerType() == 0) {
				obj.put("containerType", "仓储容器");// 容器类型
			} else if (persistentContainer.getContainerType() == 1) {
				obj.put("containerType", "运输容器");// 容器类型
			} else {
				obj.put("containerType", "未定义容器");// 容器类型
			}
			obj.put("containerLength", persistentContainer.getLongs());// 长
			obj.put("containerWidth", persistentContainer.getWide());// 宽
			obj.put("containerHeight", persistentContainer.getHigh());// 高
			obj.put("containerDeadWeight", persistentContainer.getDeadWeight());// 自重
			obj.put("containerBearWeight", persistentContainer.getBearWeight());// 承重
			obj.put("containerPermission", persistentContainer.getPermission());// 许可,牌照
			// 获取当前容器已装记录.
			List<BtPlanBiz> planBizs = planBizService.getContainerExtraInfo(projectId, planId, planPositionId,
					containerId);
			obj.put("materielCount", planBizs.size());
			BigDecimal weight = new BigDecimal(0);
			BigDecimal volume = new BigDecimal(0);
			for (BtPlanBiz btPlanBiz : planBizs) {
				BtMateriel btMateriel = materielService.getBtMateriel(btPlanBiz.getMaterielId());
				// 已装货物重量,体积
				weight = weight.add(btMateriel.getEmptyWeight());
				volume = volume.add(btMateriel.getLength().multiply(btMateriel.getWidth())
						.multiply(btMateriel.getHeight().setScale(6, BigDecimal.ROUND_HALF_UP)));// 体积
			}
			// 当前已装 重量 体积
			obj.put("extraWeight", weight);
			obj.put("extraVolume", volume);
			obj.put("takePhoto", packingListMateriel.getTakePhoto());
			// 物料信息
			obj.put("materielId", persistentMateriel.getId());// id
			obj.put("materielName", persistentMateriel.getMaterielName());// 名称
			obj.put("materielCode", persistentMateriel.getMaterielCode());// 编码
			obj.put("materielTypeName", persistentMateriel.getTypeName());// 类型名称
			obj.put("materielTypeCode", persistentMateriel.getTypeCode());// 类型编码
			obj.put("materielLength", persistentMateriel.getLength());// 长
			obj.put("materielWidth", persistentMateriel.getWidth());// 宽
			obj.put("materielHeight", persistentMateriel.getHeight());// 高
			obj.put("materielEmptyWeight", persistentMateriel.getEmptyWeight());// 净重
			obj.put("materielGrossWeight", persistentMateriel.getGrossWeight());// 毛重

			res.put("state", true);
			res.put("data", obj);
			return res.toJSONString();
		} else {
			res.put("state", false);
			res.put("msg", "请重新扫描二维码");
			return res.toJSONString();
		}

	}
}
